<?php
namespace Drupal\campusapp\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\user\Entity\User;
use Drupal\qyweixin\CorpBase;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;

/**
 * Controller routines for qrcode login form.
 */
class QrCodeLoginController extends ControllerBase {
	public function LoginPage() {
		$build=[];
		$build['#attached']['library'][] = 'campusapp/campusapp-qrlogin';
		$build['#cache']=[
			'max-age' => 0,
		];
		$build['#theme']='user-login-campusapp';
		$build['placeholder']=['#markup'=>'<div id="qrcode"/>'];
		
		return $build;
	}
	
	public function LoginPageCallback(Request $request) {
		$post_array=$request->request->all();
		\Drupal::logger('campusapp')->debug('Session: @session. Userid: @userid.',
			['@session'=>$post_array['ext']['session'], '@userid'=>$post_array['xgh']]
		);
		if($post_array['signature']==campusapp_getSign($post_array['ext'], \Drupal::config('campusapp.settings')->get('apikey'))) {
			$userid=$post_array['xgh'];
			\Drupal::moduleHandler()->alter('qyweixin_to_username', $userid);
			\Drupal::state()->set('campusapp.session.'.$post_array['ext']['session'], $userid);
			$result=[
				'e'=>9999,
				'm'=>''
			];
			$response=new JsonResponse($result);
			return $response;
		} else {
			return BadRequestHttpException();
		}
	}
	
	public function LoginResult(Request $request) {
		$sessionid=$request->query->get('sessionid');
		$result=[];
		$result['sessionid']=$sessionid;
		$uid=\Drupal::state()->get('campusapp.session.'.$sessionid);
		if(empty($uid)) $result['status']=0;
		else {
			$result['uid']=$uid;
			\Drupal::state()->delete('campusapp.session.'.$sessionid);
			$user=\user_load_by_name($uid);

			if($user==FALSE && \Drupal::config('campusapp.settings')->get('autocreation')) {
				$user=User::create();
				$user=$user->setUsername($uid)
					->setPassword(\user_password())
					->activate()
					->save();
			}

			if($user==FALSE) {
				\Drupal::logger('campusapp')->warning('Cannot login as @user, because of non-exist account.',
					['@user'=>$uid]
				);
			} else {
				\user_login_finalize($user);

				$openid=CorpBase::userConvertToOpenid($userid);
				\Drupal::service('user.data')->set('campusapp', $user->Id(), 'weixin_openid', $openid);
				\drupal_set_message(t('@user logged in via qrcode.', ['@user'=>$user->getDisplayName()]));
				$result['status']=1;
			}
		}
		$response=new JsonResponse($result);
		return $response;
	}
}
?>
